#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
FastAPI基础示例 - Python Web框架详解

本文件展示FastAPI的基本用法，包括路由定义、请求处理、响应格式等核心功能。
对比SpringBoot WebMVC，帮助Java工程师快速理解Python Web开发。

与SpringBoot对比：
1. FastAPI使用装饰器定义路由，SpringBoot使用注解
2. FastAPI自动生成API文档，SpringBoot需要额外配置
3. FastAPI内置数据验证，SpringBoot需要Bean Validation
4. FastAPI异步支持更简单，SpringBoot需要WebFlux

作者: Assistant
日期: 2024
"""

from fastapi import FastAPI, HTTPException, Depends, Query, Path, Body
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field, field_validator
from typing import List, Optional, Dict, Any
from datetime import datetime, date
from enum import Enum
import uvicorn
import logging
from contextlib import asynccontextmanager

# ============================================================================
# 1. 数据模型定义 (相当于Java的DTO/Entity)
# ============================================================================

class UserStatus(str, Enum):
    """
    用户状态枚举
    相当于Java的enum UserStatus
    """
    ACTIVE = "active"
    INACTIVE = "inactive"
    SUSPENDED = "suspended"


class UserCreateRequest(BaseModel):
    """
    创建用户请求模型
    相当于Java的UserCreateRequest DTO
    
    Python特点：
    1. 使用Pydantic自动验证和序列化
    2. Field()提供字段验证和文档
    3. validator装饰器自定义验证逻辑
    """
    name: str = Field(..., min_length=2, max_length=50, description="用户姓名")
    email: str = Field(..., pattern=r'^[\w\.-]+@[\w\.-]+\.\w+$', description="邮箱地址")
    age: int = Field(..., ge=18, le=120, description="年龄，18-120岁")
    phone: Optional[str] = Field(None, pattern=r'^1[3-9]\d{9}$', description="手机号码")
    tags: List[str] = Field(default_factory=list, description="用户标签")
    
    @field_validator('name')
    @classmethod
    def validate_name(cls, v):
        """自定义姓名验证"""
        if not v.strip():
            raise ValueError('姓名不能为空')
        if any(char.isdigit() for char in v):
            raise ValueError('姓名不能包含数字')
        return v.strip()
    
    @field_validator('tags')
    @classmethod
    def validate_tags(cls, v):
        """验证标签"""
        if len(v) > 5:
            raise ValueError('标签数量不能超过5个')
        return [tag.strip().lower() for tag in v if tag.strip()]
    
    class Config:
        """Pydantic配置"""
        json_schema_extra = {
            "example": {
                "name": "张三",
                "email": "zhangsan@example.com",
                "age": 25,
                "phone": "13800138000",
                "tags": ["developer", "python"]
            }
        }


class UserResponse(BaseModel):
    """
    用户响应模型
    相当于Java的UserResponse DTO
    """
    id: int = Field(..., description="用户ID")
    name: str = Field(..., description="用户姓名")
    email: str = Field(..., description="邮箱地址")
    age: int = Field(..., description="年龄")
    phone: Optional[str] = Field(None, description="手机号码")
    status: UserStatus = Field(..., description="用户状态")
    tags: List[str] = Field(default_factory=list, description="用户标签")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")
    
    class Config:
        """配置JSON序列化"""
        json_encoders = {
            datetime: lambda v: v.isoformat()
        }
        json_schema_extra = {
            "example": {
                "id": 1,
                "name": "张三",
                "email": "zhangsan@example.com",
                "age": 25,
                "phone": "13800138000",
                "status": "active",
                "tags": ["developer", "python"],
                "created_at": "2024-01-01T10:00:00",
                "updated_at": "2024-01-01T10:00:00"
            }
        }


class UserUpdateRequest(BaseModel):
    """
    更新用户请求模型
    所有字段都是可选的，支持部分更新
    """
    name: Optional[str] = Field(None, min_length=2, max_length=50)
    email: Optional[str] = Field(None, pattern=r'^[\w\.-]+@[\w\.-]+\.\w+$')
    age: Optional[int] = Field(None, ge=18, le=120)
    phone: Optional[str] = Field(None, pattern=r'^1[3-9]\d{9}$')
    status: Optional[UserStatus] = None
    tags: Optional[List[str]] = None
    
    @field_validator('name')
    @classmethod
    def validate_name(cls, v):
        if v is not None and not v.strip():
            raise ValueError('姓名不能为空')
        return v.strip() if v else v


class ApiResponse(BaseModel):
    """
    统一API响应格式
    相当于Java的Result<T>或ResponseEntity<T>
    """
    success: bool = Field(..., description="请求是否成功")
    message: str = Field(..., description="响应消息")
    data: Optional[Any] = Field(None, description="响应数据")
    timestamp: datetime = Field(default_factory=datetime.now, description="响应时间")
    
    class Config:
        json_encoders = {
            datetime: lambda v: v.isoformat()
        }


class PaginationResponse(BaseModel):
    """
    分页响应模型
    """
    items: List[Any] = Field(..., description="数据列表")
    total: int = Field(..., description="总数量")
    page: int = Field(..., description="当前页码")
    size: int = Field(..., description="每页大小")
    pages: int = Field(..., description="总页数")
    
    @field_validator('pages')
    @classmethod
    def calculate_pages(cls, v, info):
        """计算总页数"""
        total = info.data.get('total', 0)
        size = info.data.get('size', 10)
        return (total + size - 1) // size if size > 0 else 0


# ============================================================================
# 2. 模拟数据存储 (实际项目中会使用数据库)
# ============================================================================

class UserStorage:
    """
    用户数据存储类
    模拟数据库操作，实际项目中会使用SQLAlchemy或其他ORM
    """
    
    def __init__(self):
        self._users: Dict[int, Dict] = {}
        self._next_id = 1
        
        # 初始化一些测试数据
        self._init_test_data()
    
    def _init_test_data(self):
        """初始化测试数据"""
        test_users = [
            {
                "name": "张三",
                "email": "zhangsan@example.com",
                "age": 25,
                "phone": "13800138000",
                "tags": ["developer", "python"]
            },
            {
                "name": "李四",
                "email": "lisi@example.com",
                "age": 30,
                "phone": "13900139000",
                "tags": ["manager", "java"]
            },
            {
                "name": "王五",
                "email": "wangwu@example.com",
                "age": 28,
                "tags": ["designer", "ui"]
            }
        ]
        
        for user_data in test_users:
            self.create_user(UserCreateRequest(**user_data))
    
    def create_user(self, user_data: UserCreateRequest) -> UserResponse:
        """创建用户"""
        # 检查邮箱是否已存在
        for user in self._users.values():
            if user['email'] == user_data.email:
                raise ValueError(f"邮箱 {user_data.email} 已存在")
        
        user_id = self._next_id
        self._next_id += 1
        
        now = datetime.now()
        user = {
            "id": user_id,
            "name": user_data.name,
            "email": user_data.email,
            "age": user_data.age,
            "phone": user_data.phone,
            "status": UserStatus.ACTIVE,
            "tags": user_data.tags,
            "created_at": now,
            "updated_at": now
        }
        
        self._users[user_id] = user
        return UserResponse(**user)
    
    def get_user(self, user_id: int) -> Optional[UserResponse]:
        """获取用户"""
        user = self._users.get(user_id)
        return UserResponse(**user) if user else None
    
    def get_users(self, skip: int = 0, limit: int = 10, 
                 status: Optional[UserStatus] = None,
                 tag: Optional[str] = None) -> List[UserResponse]:
        """获取用户列表"""
        users = list(self._users.values())
        
        # 过滤条件
        if status:
            users = [u for u in users if u['status'] == status]
        
        if tag:
            users = [u for u in users if tag.lower() in [t.lower() for t in u['tags']]]
        
        # 排序（按创建时间倒序）
        users.sort(key=lambda x: x['created_at'], reverse=True)
        
        # 分页
        users = users[skip:skip + limit]
        
        return [UserResponse(**user) for user in users]
    
    def get_user_count(self, status: Optional[UserStatus] = None,
                      tag: Optional[str] = None) -> int:
        """获取用户总数"""
        users = list(self._users.values())
        
        if status:
            users = [u for u in users if u['status'] == status]
        
        if tag:
            users = [u for u in users if tag.lower() in [t.lower() for t in u['tags']]]
        
        return len(users)
    
    def update_user(self, user_id: int, user_data: UserUpdateRequest) -> Optional[UserResponse]:
        """更新用户"""
        if user_id not in self._users:
            return None
        
        user = self._users[user_id]
        
        # 检查邮箱唯一性
        if user_data.email and user_data.email != user['email']:
            for uid, u in self._users.items():
                if uid != user_id and u['email'] == user_data.email:
                    raise ValueError(f"邮箱 {user_data.email} 已存在")
        
        # 更新字段
        update_data = user_data.dict(exclude_unset=True)
        for key, value in update_data.items():
            if value is not None:
                user[key] = value
        
        user['updated_at'] = datetime.now()
        
        return UserResponse(**user)
    
    def delete_user(self, user_id: int) -> bool:
        """删除用户"""
        if user_id in self._users:
            del self._users[user_id]
            return True
        return False
    
    def search_users(self, keyword: str) -> List[UserResponse]:
        """搜索用户"""
        keyword = keyword.lower()
        results = []
        
        for user in self._users.values():
            if (keyword in user['name'].lower() or 
                keyword in user['email'].lower() or
                any(keyword in tag.lower() for tag in user['tags'])):
                results.append(UserResponse(**user))
        
        return results


# ============================================================================
# 3. 依赖注入 (相当于Java的@Autowired)
# ============================================================================

# 全局用户存储实例
user_storage = UserStorage()

def get_user_storage() -> UserStorage:
    """
    获取用户存储实例
    相当于Java的@Autowired UserService userService
    
    FastAPI的依赖注入特点：
    1. 使用Depends()声明依赖
    2. 支持嵌套依赖
    3. 自动缓存依赖实例
    4. 支持异步依赖
    """
    return user_storage


def get_current_user_id(user_id: int = Path(..., description="用户ID")) -> int:
    """
    获取当前用户ID（模拟认证）
    实际项目中会验证JWT token等
    """
    if user_id <= 0:
        raise HTTPException(status_code=400, detail="无效的用户ID")
    return user_id


# ============================================================================
# 4. 应用程序生命周期管理
# ============================================================================

@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用程序生命周期管理
    相当于Java的@PostConstruct和@PreDestroy
    """
    # 启动时执行
    logging.info("FastAPI应用启动")
    logging.info(f"初始化用户数据，当前用户数: {len(user_storage._users)}")
    
    yield  # 应用运行期间
    
    # 关闭时执行
    logging.info("FastAPI应用关闭")
    logging.info("清理资源...")


# ============================================================================
# 5. FastAPI应用实例创建
# ============================================================================

app = FastAPI(
    title="FastAPI用户管理系统",
    description="""演示FastAPI基础功能的用户管理API
    
    ## 功能特性
    
    * **用户管理**: 创建、查询、更新、删除用户
    * **数据验证**: 使用Pydantic进行请求/响应验证
    * **分页查询**: 支持分页和排序
    * **异常处理**: 统一的错误处理机制
    * **CORS支持**: 跨域资源共享配置
    
    ## 技术栈
    
    * FastAPI - 现代、快速的Web框架
    * Pydantic - 数据验证和序列化
    * Uvicorn - ASGI服务器
    """,
    version="1.0.0",
    openapi_version="3.0.2",
    docs_url="/docs",  # Swagger UI地址
    redoc_url="/redoc",  # ReDoc地址
    contact={
        "name": "API支持团队",
        "email": "support@example.com",
        "url": "https://example.com/contact"
    },
    license_info={
        "name": "MIT License",
        "url": "https://opensource.org/licenses/MIT"
    },
    servers=[
        {
            "url": "http://localhost:8000",
            "description": "开发环境"
        },
        {
            "url": "https://api.example.com",
            "description": "生产环境"
        }
    ],
    tags_metadata=[
        {
            "name": "用户管理",
            "description": "用户相关的CRUD操作",
            "externalDocs": {
                "description": "用户管理文档",
                "url": "https://docs.example.com/users"
            }
        },
        {
            "name": "首页",
            "description": "首页和基础信息"
        },
        {
            "name": "系统",
            "description": "系统状态和健康检查"
        },
        {
            "name": "统计",
            "description": "数据统计和分析"
        }
    ],
    lifespan=lifespan
)

# 配置CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该限制具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


# ============================================================================
# 6. 路由定义 (相当于Java的@RestController)
# ============================================================================

@app.get(
    "/", 
    response_class=HTMLResponse, 
    tags=["首页"],
    summary="系统首页",
    description="返回系统首页HTML，包含API文档链接和快速导航",
    responses={
        200: {
            "description": "成功返回HTML页面",
            "content": {"text/html": {"example": "<!DOCTYPE html>..."}}
        }
    }
)
async def root():
    """
    首页
    相当于Java的@GetMapping("/")
    """
    return """
    <html>
        <head>
            <title>FastAPI用户管理系统</title>
        </head>
        <body>
            <h1>欢迎使用FastAPI用户管理系统</h1>
            <p>这是一个演示FastAPI基础功能的示例应用</p>
            <ul>
                <li><a href="/docs">API文档 (Swagger UI)</a></li>
                <li><a href="/redoc">API文档 (ReDoc)</a></li>
                <li><a href="/health">健康检查</a></li>
            </ul>
        </body>
    </html>
    """


@app.get(
    "/health", 
    response_model=ApiResponse, 
    tags=["系统"],
    summary="健康检查",
    description="检查系统运行状态和各组件健康状况",
    responses={
        200: {
            "description": "系统运行正常",
            "content": {
                "application/json": {
                    "example": {
                        "status": "healthy",
                        "timestamp": "2024-01-01T12:00:00Z",
                        "version": "1.0.0",
                        "uptime": "2 days, 3 hours",
                        "checks": {
                            "database": "ok",
                            "memory": "ok",
                            "disk": "ok"
                        }
                    }
                }
            }
        }
    }
)
async def health_check():
    """
    健康检查接口
    相当于Java的@GetMapping("/health")
    """
    return ApiResponse(
        success=True,
        message="服务运行正常",
        data={
            "status": "healthy",
            "timestamp": datetime.now(),
            "version": "1.0.0"
        }
    )


@app.post(
    "/users", 
    response_model=ApiResponse, 
    status_code=201, 
    tags=["用户管理"],
    summary="创建新用户",
    description="创建一个新的用户账户，需要提供用户基本信息",
    responses={
        201: {
            "description": "用户创建成功",
            "model": ApiResponse
        },
        400: {
            "description": "请求参数错误",
            "content": {
                "application/json": {
                    "example": {"success": False, "message": "邮箱已存在", "data": None}
                }
            }
        },
        422: {
            "description": "数据验证失败",
            "content": {
                "application/json": {
                    "example": {
                        "detail": [
                            {
                                "loc": ["body", "email"],
                                "msg": "field required",
                                "type": "value_error.missing"
                            }
                        ]
                    }
                }
            }
        }
    }
)
async def create_user(
    user_data: UserCreateRequest,
    storage: UserStorage = Depends(get_user_storage)
):
    """
    创建用户
    相当于Java的@PostMapping("/users")
    
    FastAPI特点：
    1. 自动解析JSON请求体为Pydantic模型
    2. 自动验证数据格式和约束
    3. 自动生成API文档
    4. 支持依赖注入
    """
    try:
        user = storage.create_user(user_data)
        logger.info(f"创建用户成功: {user.name} ({user.email})")
        
        return ApiResponse(
            success=True,
            message="用户创建成功",
            data=user
        )
    except ValueError as e:
        logger.warning(f"创建用户失败: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"创建用户异常: {str(e)}")
        raise HTTPException(status_code=500, detail="内部服务器错误")


@app.get(
    "/users/{user_id}", 
    response_model=ApiResponse, 
    tags=["用户管理"],
    summary="获取用户详情",
    description="根据用户ID获取用户详细信息",
    responses={
        200: {
            "description": "成功获取用户信息",
            "model": ApiResponse
        },
        404: {
            "description": "用户不存在",
            "content": {
                "application/json": {
                    "example": {"success": False, "message": "用户不存在", "data": None}
                }
            }
        }
    }
)
async def get_user(
    user_id: int = Depends(get_current_user_id),
    storage: UserStorage = Depends(get_user_storage)
):
    """
    获取用户详情
    相当于Java的@GetMapping("/users/{id}")
    
    路径参数特点：
    1. 自动类型转换和验证
    2. 支持路径参数约束
    3. 自动生成文档
    """
    user = storage.get_user(user_id)
    if not user:
        raise HTTPException(status_code=404, detail=f"用户 {user_id} 不存在")
    
    logger.info(f"获取用户详情: {user.name}")
    return ApiResponse(
        success=True,
        message="获取用户成功",
        data=user
    )


@app.get(
    "/users", 
    response_model=ApiResponse, 
    tags=["用户管理"],
    summary="获取用户列表",
    description="分页获取用户列表，支持状态筛选和标签过滤",
    responses={
        200: {
            "description": "成功获取用户列表",
            "model": ApiResponse
        }
    }
)
async def get_users(
    page: int = Query(1, ge=1, description="页码，从1开始", example=1),
    size: int = Query(10, ge=1, le=100, description="每页大小，1-100", example=10),
    status: Optional[UserStatus] = Query(None, description="用户状态过滤"),
    tag: Optional[str] = Query(None, description="标签过滤", example="developer"),
    storage: UserStorage = Depends(get_user_storage)
):
    """
    获取用户列表（分页）
    相当于Java的@GetMapping("/users")
    
    查询参数特点：
    1. Query()定义查询参数
    2. 支持默认值和验证
    3. 自动类型转换
    4. 可选参数支持
    """
    skip = (page - 1) * size
    
    users = storage.get_users(skip=skip, limit=size, status=status, tag=tag)
    total = storage.get_user_count(status=status, tag=tag)
    
    pagination = PaginationResponse(
        items=users,
        total=total,
        page=page,
        size=size
    )
    
    logger.info(f"获取用户列表: 页码={page}, 大小={size}, 总数={total}")
    return ApiResponse(
        success=True,
        message="获取用户列表成功",
        data=pagination
    )


@app.put(
    "/users/{user_id}", 
    response_model=ApiResponse, 
    tags=["用户管理"],
    summary="更新用户信息",
    description="根据用户ID更新用户信息，支持部分更新，只更新提供的字段",
    responses={
        200: {
            "description": "用户信息更新成功",
            "model": ApiResponse
        },
        404: {
            "description": "用户不存在",
            "content": {
                "application/json": {
                    "example": {"success": False, "message": "用户不存在", "data": None}
                }
            }
        },
        400: {
            "description": "更新参数错误",
            "content": {
                "application/json": {
                    "example": {"success": False, "message": "邮箱已被其他用户使用", "data": None}
                }
            }
        }
    }
)
async def update_user(
    user_data: UserUpdateRequest,
    user_id: int = Depends(get_current_user_id),
    storage: UserStorage = Depends(get_user_storage)
):
    """
    更新用户信息
    相当于Java的@PutMapping("/users/{id}")
    
    支持部分更新，只更新提供的字段
    """
    try:
        user = storage.update_user(user_id, user_data)
        if not user:
            raise HTTPException(status_code=404, detail=f"用户 {user_id} 不存在")
        
        logger.info(f"更新用户成功: {user.name}")
        return ApiResponse(
            success=True,
            message="用户更新成功",
            data=user
        )
    except ValueError as e:
        logger.warning(f"更新用户失败: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"更新用户异常: {str(e)}")
        raise HTTPException(status_code=500, detail="内部服务器错误")


@app.delete(
    "/users/{user_id}", 
    response_model=ApiResponse, 
    tags=["用户管理"],
    summary="删除用户",
    description="根据用户ID删除用户账户",
    responses={
        200: {
            "description": "用户删除成功",
            "model": ApiResponse
        },
        404: {
            "description": "用户不存在",
            "content": {
                "application/json": {
                    "example": {"success": False, "message": "用户不存在", "data": None}
                }
            }
        }
    }
)
async def delete_user(
    user_id: int = Depends(get_current_user_id),
    storage: UserStorage = Depends(get_user_storage)
):
    """
    删除用户
    相当于Java的@DeleteMapping("/users/{id}")
    """
    success = storage.delete_user(user_id)
    if not success:
        raise HTTPException(status_code=404, detail=f"用户 {user_id} 不存在")
    
    logger.info(f"删除用户成功: ID={user_id}")
    return ApiResponse(
        success=True,
        message="用户删除成功",
        data={"deleted_user_id": user_id}
    )


@app.get(
    "/users/search", 
    response_model=ApiResponse, 
    tags=["用户管理"],
    summary="搜索用户",
    description="根据关键词搜索用户，支持按姓名、邮箱、标签搜索",
    responses={
        200: {
            "description": "搜索完成",
            "model": ApiResponse
        }
    }
)
async def search_users(
    q: str = Query(..., min_length=1, description="搜索关键词", example="张三"),
    storage: UserStorage = Depends(get_user_storage)
):
    """
    搜索用户
    支持按姓名、邮箱、标签搜索
    """
    users = storage.search_users(q)
    
    logger.info(f"搜索用户: 关键词='{q}', 结果数={len(users)}")
    return ApiResponse(
        success=True,
        message=f"搜索完成，找到 {len(users)} 个用户",
        data=users
    )


@app.get(
    "/users/stats", 
    response_model=ApiResponse, 
    tags=["统计"],
    summary="用户统计",
    description="获取用户统计信息，包括用户数量、状态分布、标签分布等",
    responses={
        200: {
            "description": "成功获取统计信息",
            "content": {
                "application/json": {
                    "example": {
                        "total_users": 150,
                        "status_distribution": {
                            "active": 120,
                            "inactive": 20,
                            "suspended": 10
                        },
                        "tag_distribution": {
                            "developer": 80,
                            "manager": 30,
                            "designer": 40
                        },
                        "generated_at": "2024-01-01T12:00:00Z"
                    }
                }
            }
        }
    }
)
async def get_user_stats(
    storage: UserStorage = Depends(get_user_storage)
):
    """
    获取用户统计信息
    """
    total_users = storage.get_user_count()
    active_users = storage.get_user_count(status=UserStatus.ACTIVE)
    inactive_users = storage.get_user_count(status=UserStatus.INACTIVE)
    suspended_users = storage.get_user_count(status=UserStatus.SUSPENDED)
    
    # 统计标签分布
    all_users = storage.get_users(skip=0, limit=1000)
    tag_counts = {}
    for user in all_users:
        for tag in user.tags:
            tag_counts[tag] = tag_counts.get(tag, 0) + 1
    
    stats = {
        "total_users": total_users,
        "status_distribution": {
            "active": active_users,
            "inactive": inactive_users,
            "suspended": suspended_users
        },
        "tag_distribution": tag_counts,
        "generated_at": datetime.now()
    }
    
    return ApiResponse(
        success=True,
        message="获取统计信息成功",
        data=stats
    )


# ============================================================================
# 7. 异常处理 (相当于Java的@ExceptionHandler)
# ============================================================================

@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc: HTTPException):
    """
    HTTP异常处理器
    相当于Java的@ExceptionHandler(HttpException.class)
    """
    logger.warning(f"HTTP异常: {exc.status_code} - {exc.detail}")
    return JSONResponse(
        status_code=exc.status_code,
        content=ApiResponse(
            success=False,
            message=exc.detail,
            data=None
        ).dict()
    )


@app.exception_handler(Exception)
async def general_exception_handler(request, exc: Exception):
    """
    通用异常处理器
    相当于Java的@ExceptionHandler(Exception.class)
    """
    logger.error(f"未处理异常: {type(exc).__name__} - {str(exc)}")
    return JSONResponse(
        status_code=500,
        content=ApiResponse(
            success=False,
            message="内部服务器错误",
            data=None
        ).dict()
    )


# ============================================================================
# 8. 启动配置
# ============================================================================

if __name__ == "__main__":
    # 开发环境启动配置
    # 相当于Java的application.yml配置
    uvicorn.run(
        "01_fastapi_basic:app",  # 应用模块:实例名
        host="0.0.0.0",          # 监听地址
        port=8000,               # 监听端口
        reload=True,             # 开发模式自动重载
        log_level="info",        # 日志级别
        access_log=True          # 访问日志
    )


# ============================================================================
# 9. FastAPI vs SpringBoot 对比总结
# ============================================================================

"""
FastAPI vs SpringBoot WebMVC 对比总结:

1. 路由定义:
   - FastAPI: 使用装饰器 @app.get("/users")
   - SpringBoot: 使用注解 @GetMapping("/users")

2. 数据验证:
   - FastAPI: Pydantic自动验证，声明式约束
   - SpringBoot: Bean Validation，需要@Valid注解

3. 依赖注入:
   - FastAPI: Depends()函数，支持嵌套依赖
   - SpringBoot: @Autowired注解，基于类型注入

4. 异常处理:
   - FastAPI: @app.exception_handler装饰器
   - SpringBoot: @ExceptionHandler注解

5. API文档:
   - FastAPI: 自动生成Swagger/OpenAPI文档
   - SpringBoot: 需要SpringDoc或Swagger配置

6. 异步支持:
   - FastAPI: 原生async/await支持
   - SpringBoot: 需要WebFlux或@Async

7. 配置管理:
   - FastAPI: Python代码配置，环境变量
   - SpringBoot: application.yml/properties文件

8. 中间件:
   - FastAPI: add_middleware()方法
   - SpringBoot: Filter或Interceptor

9. 启动方式:
   - FastAPI: uvicorn ASGI服务器
   - SpringBoot: 内嵌Tomcat/Jetty

10. 开发体验:
    - FastAPI: 更简洁的代码，更快的开发速度
    - SpringBoot: 更成熟的生态，更多的企业级功能
"""